<template>
  <a-modal title-align="start" :title="title" :mask-closable="false" v-model:visible="showvisible" @cancel="showvisible = false" :width="600">
    <div class="flex">
      <div class="img-con-left">
        <div class="common-text">鼠标拖动设置首图</div>
        <div style="height: 80px; width: 80px">
          <a-upload class="fl mb10" v-loading="uplaodLoading" :show-file-list="false" list-type="picture-card" action="/" :on-before-upload="uploadBefore" />
        </div>

        <a-image-preview-group infinite>
          <div class="product-picture-container">
            <div class="mb10 img" v-for="(item, index) in productPicList" :key="index">
              <icon-close-circle class="delete-icon" @click="productPicList.splice(index, 1)" />
              <a-image :src="item.url" width="80" height="80" />
            </div>
          </div>
        </a-image-preview-group>
      </div>
      <div class="form-right">
        <a-form auto-label-width ref="formRef" size="medium" :model="form">
          <a-form-item label="SKU:" field="sku" :rules="[{ required: type == 'add', message: '请输入SKU' }]">
            <a-input v-if="type == 'add'" v-model="form.sku" placeholder="请输入sku" allow-clear style="width: 280px" />
            <a-button v-if="type == 'add'" class="ml10 mr10" type="text" @click="ceateSKU">生成SKU</a-button>
            <a-popover v-if="type == 'add'">
              <icon-question-circle-fill style="font-size: 20px" />
              <template #content>
                <div v-if="curTabTitle == '链条'">链条的SKU生成规则LT+6位随机数</div>
                <div v-else>石头的SKU生成规则ST+6位随机数</div>
              </template>
            </a-popover>
            <div v-if="type != 'add'">{{ form.sku }}</div>
          </a-form-item>
          <a-form-item label="名称:" field="skuName" :rules="[{ required: true, message: '请输入名称' }]">
            <a-input v-model="form.skuName" placeholder="请输入名称" allow-clear style="width: 280px" />
            <a-button class="ml10 mr10" type="text" @click="createName">属性值生成</a-button>
            <a-popover>
              <icon-question-circle-fill style="font-size: 20px" />
              <template #content>
                <div>用属性值组成名称</div>
                <div v-if="curTabTitle == '链条'">
                  <div> 材质+链条宽度+链型+链条长度+扣子+电镀颜色</div>
                </div>
                <div v-else>石头类型+石头颜色+形状+切割工艺+规格尺寸</div>
              </template>
            </a-popover>
          </a-form-item>
          <a-form-item v-for="(item, index) of propList" :key="index" :label="item.name + ':'" :field="item.name" :rules="[{ required: item.propRequired, message: [1, 2].includes(item.type) ? `请选择${item.name}` : `请输入` }]">
            <div v-if="item.type == 1">
              <a-select allow-clear v-model="form[item.name]" allow-search placeholder="请选择" style="width: 280px">
                <a-option v-for="(optionItem, optionIndex) of item.propValueList" :key="optionIndex" :label="optionItem.propValue" :value="optionItem.propValue"></a-option>
              </a-select>
            </div>
            <div v-if="item.type == 2">
              <a-select allow-clear v-model="form[item.name]" allow-search multiple placeholder="请选择" style="width: 280px">
                <a-option v-for="(optionItem, optionIndex) of item.propValueList" :key="optionIndex" :label="optionItem.propValue" :value="optionItem.propValue"></a-option>
              </a-select>
            </div>
            <div v-if="item.type == 4">
              <a-input allow-clear v-model="form[item.name]" placeholder="请输入" style="width: 280px" />
            </div>
          </a-form-item>
        </a-form>
      </div>
    </div>

    <template #footer class="modal-footer">
      <a-button @click="showvisible = false">取消</a-button>
      <a-button type="primary" :loading="submitLoading" @click="submit">确定</a-button>
    </template>
  </a-modal>
</template>

<script lang="ts" setup>
  import { ref, computed, onMounted, nextTick } from 'vue'
  import { saveOrUpdateById } from '@/api/product'
  import { OSSUpload } from '@/utils/ossUpload'
  import { Message } from '@arco-design/web-vue'
  import Sortable from 'sortablejs'
  import _ from 'lodash-es'
  const props = defineProps(['modelValue', 'type', 'info', 'categoryId', 'propList', 'curTabTitle'])
  const emits = defineEmits(['save', 'update:modelValue'])

  const formRef = ref()
  const title = computed(() => {
    return `${props.type == 'add' ? '新增' : '编辑'}${props.curTabTitle}`
  })
  const showvisible = computed({
    get() {
      return props.modelValue
    },
    set(val) {
      emits('update:modelValue', val)
    },
  })
  const uplaodLoading = ref(false)
  const submitLoading = ref(false)
  const form = ref<any>({})
  const productPicList = ref<Array<any>>([])

  const uploadBefore = async (file: File) => {
    try {
      uplaodLoading.value = true
      const res: any = await OSSUpload(file)
      let obj = {
        url: res?.url,
      }
      productPicList.value.push(obj)
    } catch (error) {}
    uplaodLoading.value = false
  }

  const ceateSKU = () => {
    let num = Math.floor(100000 + Math.random() * 900000)
    if (props.curTabTitle == '链条') {
      form.value.sku = 'LT' + num
    } else {
      form.value.sku = 'ST' + num
    }
  }

  const createName = () => {
    let arr = props.propList.map((e: any) => e.name)
    let text = ''
    arr.forEach((e: any) => {
      if (form.value[e] && e != '备注') text += form.value[e]
    })

    form.value.skuName = text
  }

  const submit = async () => {
    // if (!productPicList.value[0]) return Message.error('请上传图片')
    const valid = await formRef.value.validate()
    if (valid) return
    let params: any = {
      ...form.value,
      category: {
        id: props.categoryId,
        name: props.curTabTitle,
      },
      sku: form.value.sku,
      skuName: form.value.skuName,
      productPicList: productPicList.value,
      status: 'ACTIVE',
      propList: [],
    }
    let propResArr: any = []
    props.propList.forEach((e: any) => {
      if (form.value[e.name]) {
        let item = e.propValueList.find((el: any) => el.propValue == form.value[e.name])
        let obj = {
          code: e.code,
          name: e.name,
          nameEn: e.nameEn,
          propId: e.id,
          valueStr: '',
          valueStrList: [],
          type: e.type,
        }

        if (form.value[e.name] instanceof Array) {
          obj.valueStrList = form.value[e.name]
        } else {
          obj.valueStr = form.value[e.name]
        }

        propResArr.push(obj)
      }
    })
    params.propList = propResArr
    try {
      submitLoading.value = true
      const res: any = await saveOrUpdateById(params)
      if (res) {
        Message.success(`${props.curTabTitle}创建成功`)
        emits('save')
        showvisible.value = false
      }
    } catch (error) {}
    submitLoading.value = false
  }

  const init = () => {
    form.value = _.cloneDeep(props.info) || {}
    let propsList = props.info?.propList || []
    propsList.forEach((e: any) => {
      if (e?.valueStr) {
        form.value[e.name] = e.valueStr
      } else if (e.valueStrList && e.valueStrList[0]) {
        form.value[e.name] = e.valueStrList
      }
      // if (e?.valueStr) form.value[e.name] = e.valueStr
      // if (e.valueStrList && e.valueStrList[0]) form.value[e.name] = e.valueStrList
    })
    productPicList.value = form.value?.productPicList || []
    setTimeout(() => {
      rowDrop()
    }, 100)
  }

  const rowDrop = () => {
    const body: any = document.querySelector('.product-picture-container')
    Sortable.create(body, {
      animation: 200, // 定义排序动画的时间
      forceFallback: true,
      onEnd(evt: any) {
        productPicList.value.splice(evt.newIndex, 0, productPicList.value.splice(evt.oldIndex, 1)[0])
        var newArray = productPicList.value.slice(0)
        productPicList.value = []
        nextTick(() => {
          productPicList.value = newArray
        })
      },
    })
  }

  onMounted(init)
</script>

<style lang="less" scoped>
  :deep(.arco-upload-picture-card) {
    width: 80px;
    height: 80px;
  }
  :deep(.arco-upload-list-picture) {
    width: 80px;
    height: 80px;
  }

  :deep(.arco-upload-picture-card-text) {
    font-size: 26px;
  }

  .custom-uplaod-btn {
    width: 80px;
    height: 80px;
    line-height: 80px;
    text-align: center;
    background: var(--color-fill-2);
    border: 1px dashed var(--color-neutral-3);
    border-radius: var(--border-radius-small);
  }

  .img-con-left {
    width: 100px;
    .img {
      position: relative;
    }
    .delete-icon {
      font-size: 24px;
      font-weight: 700;
      position: absolute;
      top: 0px;
      right: 6px;
      z-index: 1;
      cursor: pointer;
    }
  }

  .form-right {
    flex: 1;
    margin-left: 10px;
  }
</style>
